define(['jquery'], function ($) {

	/**
	 * 上传附件
	 * @param {[object]} opt 配置参数
	 */
	function UploadFile (opt) {
		this.opt = {
			selector: '.upload-attachment', 
			file_elem: $('#file-select'),
			form_selector: '#upload-form'
		}
		this.opt = $.extend({}, this.opt, opt);

		this.current_elem = null; // 当期点击的元素

		this.init();

	}

	/**
	 * 上传附件
	 * @param  {[string]} selector    上传附件按钮的class或id,  .select || #select
	 * @param  {[input]} file_elem    文件选择input, $('#file-select')
	 * @param  {[string]} form_selector 上传文件的表单， #upload-form
	 * @return {[type]}               [description]
	 */
	UploadFile.prototype.init = function () {

		var _this = this;

		// 绑定点击事件
		$(document).on('click', _this.opt.selector, function (e) {
			_this.opt.file_elem.click();
			_this.current_elem = $(this);
		})



		_this.opt.file_elem.on('change', function () {
			$('.loading').show();
			var formdata = new FormData($(_this.opt.form_selector)[0]);

			_this.ajaxPost(formdata).then(function (json) {
	                _this.callBack(json);
				}).catch(function (err) {
					console.log(err)
					alert('上传失败');
		 			$('.loading').hide();
	            });
		});
	}



	/*
	 * 获取文件后缀名
	 * @param: file => 选中的文件
	 * @return: undefined 或者 文件名
	 */
	UploadFile.prototype.getSuffix = function (file) {

		var type; // 文件类型

		switch (file){
            case "doc":
            case "txt":
            case "docx":
                type = "doc.png";
                break;
            case "wps":
            case "xls":
            case "xlsx":
                type = "xls.png";
                break;
            case "pdf":
                type = "pdf.png";
                break;
            case "zip":
            case "rar":
                type = "rar.png";
                break;
            case "png":
            case "jpg":
            case "jpeg":
            case "webp":
            case "gif":
                type = "jpg.png";
                break;

            default:
                break;
        }

        return type;

	}


	/*
	 * ajax上传文件
	 * @param: data => ajax提交的数据
	 * @return promise对象
	 */
	UploadFile.prototype.ajaxPost = function (data) {

	 	return new Promise(function (resolve, reject) {
	 		$.ajax({
	 			url: '/Api/Upload/ajax_uploadFile',
	 			type: 'post',
	 			datatype: 'json',
	 			data: data,
	 			timeout: 30000,
	 			processData: false,
				contentType: false,
	 			success: function (json) {
	 				json.code == 0 ? alert(json.msg) : resolve(json);
	 			},
	 			error: function () {
	 				alert('上传失败');
	 				$('.loading').hide();
	 			}
	 		})
	 	});
	}

	/**
	 * 上传文件成功之后的回调函数
	 * @param: json => ajax返回的数据
	 * @param: data => 被上传文件的信息
	 */
	UploadFile.prototype.callBack =function (json, data) {
		var _this = this;
		json = JSON.parse(json)
		var str = 'png/PNG/jpg/JPG/jpeg/JPEG/gif/GIF/webp/WEBP';
			type = json.type_img;
		var hideclass = new RegExp(type).test(str) ? '' : 'hide',
			num = $(_this.current_elem).data('num');

		var tem = '<span class="file-item">' +
                	'<img src="/static/img/' + _this.getSuffix(type) + '" class="icon" style="height: 17px">' +
                	'<span class="fileName">' + json.filename +'</span>' +
                	'<input type="hidden" name="activity_attachment_'+ num +'" value="' + json.file_id + '" >' +
                	'<a data-toggle="modal" data-target="#imgModal" data-img="'+ json.url +'" class="color-blue preview '+ hideclass +'">预览</a>' +
                	'<a class="color-blue" href="' + json.url + '">下载</a>' +
                	'<a class="del color-blue">删除</a>' +
                '</span>';
                
        _this.current_elem.addClass('hide').siblings('.file-item').remove();
        _this.current_elem.before(tem);

        $('.loading').hide();
	} 


	// 附件删除
	$(document).on('click', '.del', function () {
		$(this).parents('td').find('.upload-attachment').removeClass('hide');
		$(this).parents('.file-item').remove();
	});

	// 图片预览
	$(document).on('click', '.preview', function () {
		var imgurl = $(this).data('img');
		$('#imgModal').find('.preview-img').attr('src', imgurl);
	});

	return UploadFile;
});